package com.mybatis.aop.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class AOPAspect {

    @Pointcut(value = "execution(* com.mybatis.aop.serviceImpl.UserServiceImpl.get*(..))")  //注意这里是全文件匹配函数
    public void getPoint() {
    }

    @Pointcut(value = "execution(* com.mybatis.aop.serviceImpl.UserServiceImpl.set*(..))")  //注意这里是全文件匹配函数
    public void setPoint() {
    }

    @Before("getPoint()")
    public void getPointAcc1(){
        System.out.println("BeforeGetPoint");
    }

    @After("getPoint()")
    public void getPointAcc2(){
        System.out.println("AfterGetPoint");
    }

    @Before("setPoint()")
    public void setPointAcc1(){
        System.out.println("BeforeSetPoint");
    }

    @After("setPoint()")
    public void setPointAcc2(){
        System.out.println("AfterSetPoint");
    }

    @Around("getPoint()")
    public Object getDoAround(ProceedingJoinPoint pjp){
        ThreadLocal<Long> startTime = new ThreadLocal<>();
        startTime.set(System.currentTimeMillis());
        System.out.println("我是环绕通知执行");
        Object obj;
        try{
            obj = pjp.proceed();  //启动目标方法执行
            System.out.println("执行返回值 : " + obj);
            Signature s = pjp.getSignature();
            System.out.println(pjp.getSignature().getName()+"方法执行耗时: " + (System.currentTimeMillis() - startTime.get()));
        } catch (Throwable throwable) {
            obj=throwable.toString();
        }
        return obj;
    }

    @Around("setPoint()")
    public Object setDoAround(ProceedingJoinPoint pjp){
        ThreadLocal<Long> startTime = new ThreadLocal<>();
        startTime.set(System.currentTimeMillis());
        System.out.println("我是环绕通知执行");
        Object obj;
        try{
            obj = pjp.proceed();  //启动目标方法执行
            System.out.println("执行返回值 : " + obj);
            Signature s = pjp.getSignature();
            System.out.println(pjp.getSignature().getName()+"方法执行耗时: " + (System.currentTimeMillis() - startTime.get()));
        }catch (Throwable throwable) {
            obj=throwable.toString();
        }
        return obj;
    }

    /**
     * 执行完请求可以做的
     * @param result
     * @throws Throwable
     */
    @AfterReturning(returning = "result", pointcut = "getPoint()||setPoint()")
    public void doAfterReturning(Object result){
        System.out.println("大家好，我是@AfterReturning，他们都秀完了，该我上场了"+result);
    }


}
